// 引入需要用到的 antd 组件
import {
  Table as AntdTable,
  Button,
  Form,
  Input,
  Modal,
  Select,
  Switch,
  message,
} from "antd";
// 引入 mockjs，用于模拟数据
// 引入 React hooks 相关依赖
import React, { useEffect, useState } from "react";
// 引入 umi-request，用于发送 HTTP 请求
import request from "umi-request";
// 引入自定义的级联选择器组件
import CascadingSelect from "../Select/Cascader";
// 引入样式文件
import "./table.scss";

// 发送 GET 请求获取广告列表数据
const response = await request.get("/api/adver");

// 用户数据结构
interface User {
  id: number;
  name: string;
  age: number;
  address: string;
}

// 表格组件的 props 类型定义
interface TableProps {
  dataSource: User[]; // 用户数据列表

  onCreate?: (user: User) => void; // 创建用户回调函数
  onUpdate?: (user: User) => void; // 更新用户回调函数
  onDelete?: (id: number) => void; // 删除用户回调函数
  onSelectChange?: (selectedRowKeys: number[]) => void; // 选中行变更回调函数
}

// 表格组件
const Table: React.FC<TableProps> = ({
  dataSource,
  onCreate = () => {},
  onUpdate = () => {},
  onDelete = () => {},
  onSelectChange = () => {},
}) => {
  const [loading, setLoading] = useState(false); // 表格 loading 状态
  const [visible, setVisible] = useState(false); // Modal 显示状态
  const [form] = Form.useForm(); // 创建表单
  const [pagination, setPagination] = useState({
    current: 1, // 当前页码
    pageSize: 7, // 每页条数
    total: dataSource.length, // 数据总数
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]); // 选中的行数据
  const [states, useStates] = useState(response); // 声明状态 states，并初始化为 response 的值
  console.log(states);

  useEffect(() => {
    // 模拟异步请求数据
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1000);
  }, [pagination.current, pagination.pageSize]);

  const handleCreate = () => {
    // 显示 Modal
    setVisible(true);
  };

  const handleUpdate = (record: User) => {
    // 编辑用户
    setVisible(true);
    form.setFieldsValue(record); // 设置表单的初始值
    form.setFieldsValue({ id: record.id }); // 在表单中增加 id 字段，以便区分添加和更新操作
  };

  const handleDelete = (id: number) => {
    // 删除用户
    Modal.confirm({
      title: "确认删除？",
      onOk: () => {
        onDelete(id);
        message.success("删除成功");
      },
    });
  };

  const handleOk = () => {
    // 提交表单
    form.validateFields().then((values) => {
      const user = {
        ...values,
      };
      if (user.id) {
        // 如果 id 存在，则为更新操作
        onUpdate(user);
        message.success("编辑成功");
      } else {
        user.id = dataSource.length + 1; // id 不存在则视为添加，并生成新 id
        onCreate(user);
        message.success("创建成功");
      }
      form.resetFields(); // 重置表单
      setVisible(false); // 隐藏 Modal
    });
  };

  const handleCancel = () => {
    // 取消操作，重置表单并隐藏 Modal
    form.resetFields();
    setVisible(false);
  };

  const handlePageChange = (current: number, pageSize?: number) => {
    // 页码变更事件处理函数
    setPagination({
      current,
      pageSize: pageSize || pagination.pageSize,
      total: dataSource.length,
    });
  };

  const handlePageSizeChange = (current: number, pageSize: number) => {
    // 每页条数变更事件处理函数
    setPagination({
      current,
      pageSize,
      total: dataSource.length,
    });
  };

  const handleSelectionChange = (selectedRowKeys: any[]) => {
    // 选中行变更事件处理函数
    setSelectedRowKeys(selectedRowKeys);
    onSelectChange(selectedRowKeys);
  };

  const columns: any = [
    {
      title: "ID",
      dataIndex: "id",
      align: "center", // 设置表头居中对齐
      render: (text: any) => <div style={{ textAlign: "center" }}>{text}</div>,
    },
    {
      title: "广告位名称",
      dataIndex: "name",
      width: "10%",
      minWidth: 80,
      align: "center", // 设置表头居中对齐
      render: (text: any) => <div style={{ textAlign: "center" }}>{text}</div>,
    },
    {
      title: "广告位类型",
      dataIndex: "age",
      width: "20%",
      minWidth: 80,
      align: "center", // 设置表头居中对齐
      render: (text: any) => <div style={{ textAlign: "center" }}>{text}</div>,
    },
    {
      title: "地址",
      dataIndex: "address",
      width: "20%",
      minWidth: 80,
      align: "center", // 设置表头居中对齐
      render: (text: any) => <div style={{ textAlign: "center" }}>{text}</div>,
    },
    {
      title: "状态",
      width: "20%",
      minWidth: 80,
      align: "center", // 设置表头居中对齐
      render: (text: any) => (
        <div style={{ textAlign: "center" }}>
          <Switch
            checkedChildren="开启"
            unCheckedChildren="关闭"
            defaultChecked={true}
          />
        </div>
      ),
    },
    {
      title: "操作",
      width: "30%",
      minWidth: 80,
      align: "center", // 设置表头居中对齐
      render: (_: any, record: User) => (
        <>
          <Button
            type="link"
            onClick={() => handleCreate}
            className="handleUpdate"
          >
            添加广告
          </Button>
          <Button
            type="link"
            onClick={() => handleUpdate(record)}
            className="handleUpdate"
          >
            广告管理
          </Button>
          <Button
            type="link"
            onClick={() => handleCreate}
            className="handleUpdate2"
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            onClick={() => handleDelete(record.id)}
            className="handleDelete"
            style={{ color: "white" }}
          >
            删除
          </Button>
        </>
      ),
    },
  ];

  return (
    <div style={{ fontSize: "12px", lineHeight: 1.5 }}>
      <div style={{ marginBottom: 16, fontSize: "12px", lineHeight: 1.5 }}>
        <div className="select">
          <CascadingSelect></CascadingSelect>
        </div>
        <Button type="primary" onClick={handleCreate} className="handleCreate">
          添加广告位
        </Button>
        <Button
          type="primary"
          danger
          disabled={selectedRowKeys.length === 0}
          style={{ marginLeft: 8 }}
          onClick={() => {
            Modal.confirm({
              title: "确认删除？",
              onOk: () => {
                selectedRowKeys.forEach((id) => onDelete(id));
                setSelectedRowKeys([]);
                message.success("删除成功");
              },
            });
          }}
        >
          批量删除
        </Button>
      </div>
      <AntdTable
        scroll={{ x: "max-content" }}
        style={{ fontSize: "12px", lineHeight: 1.5 }}
        rowKey="id"
        dataSource={dataSource.slice(
          (pagination.current - 1) * pagination.pageSize,
          pagination.current * pagination.pageSize
        )}
        columns={columns}
        loading={loading}
        pagination={{
          ...pagination,
          onChange: handlePageChange,
          onShowSizeChange: handlePageSizeChange,
        }}
        rowSelection={{
          selectedRowKeys,
          onChange: handleSelectionChange,
        }}
      />
      <Modal
        title="城市管理"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
          <Form.Item name="id" noStyle>
            <Input type="hidden" />
          </Form.Item>
          <Form.Item name="name" label="姓名" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="age" label="年龄" rules={[{ required: true }]}>
            <Input type="number" />
          </Form.Item>
          <Form.Item name="address" label="地址" rules={[{ required: true }]}>
            <Select style={{ width: "100%" }} popupMatchSelectWidth>
              <Select.Option value="北京市">北京市</Select.Option>
              <Select.Option value="上海市">上海市</Select.Option>
              <Select.Option value="广州市">广州市</Select.Option>
              <Select.Option value="深圳市">深圳市</Select.Option>
              <Select.Option value="杭州市">杭州市</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default () => {
  const [dataSource, setDataSource] = useState<User[]>(response);

  const handleCreate = (user: User) => {
    setDataSource([...dataSource, user]);
  };

  const handleUpdate = (user: User) => {
    setDataSource(
      dataSource.map((item) => (item.id === user.id ? user : item))
    );
  };

  const handleDelete = (id: number) => {
    setDataSource(dataSource.filter((item) => item.id !== id));
  };

  const handleSelectChange = (selectedRowKeys: number[]) => {
    console.log(selectedRowKeys);
  };

  return (
    <Table
      dataSource={dataSource}
      onCreate={handleCreate}
      onUpdate={handleUpdate}
      onDelete={handleDelete}
      onSelectChange={handleSelectChange}
    />
  );
};
